<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>博客首页jquery</title>
    <link rel="stylesheet" href="./css/bootstrap.css">
    <style>
        .avatarUrl{
            width: 40px;
            height: 40px;
            float:left;
            border-radius: 50%;
            /*border: 1px solid black;*/
        }
        .nickname{
            margin-left: 50px;

        }
        .createdTime{
            margin-left: 50px;
            color: #999999;
        }
        .clear:after{
            display: block;
            content: '';
            clear: both;
        }
        .item-content{
            margin-top: 10px;

            min-height: 100px;
            padding: 10px;
        }
        .item-content:hover{

        }
        .list-group-item{
            margin-bottom: 15px;
            border-top: 0;
            border-left:0;
            border-right:0;
        }

        .list-group-item:hover{
            background-color:#eeeeee;
            cursor: pointer;
        }
        .blog-img{
            width: 150px;
            /*margin-top: 10px;*/
            margin: 10px;
        }
        .imgs{
            display: flex;
            flex-wrap: wrap;
            width: 550px;
            border: 1px dashed #aaa;
        }
        .post-img{
            float: left;
            text-align: center;

        }
        .post-img-add{
            float: left;
            font-size: 100px;
            border: 1px solid #666;
            text-align: center;
            margin-top: 10px;
            width: 100px;
        }
        .post-img-add:hover{
            cursor: pointer;
            background-color: #c7ddef;
        }

        .page-header{
            display: flex;
            justify-content: space-between;
        }
        .login-div{
            display: flex;
            align-items: center;
        }
        .login-div img{
            vertical-align: middle;
        }

        .fadiv{
            margin-bottom: 20px;
            text-align: right;
        }
        .welcome{
            margin: 0 10px;
            /*width:100px;*/
            text-align: center;
        }
        .welcome img{
            width: 40px;
            border-radius: 10px;
        }
    </style>
    <script src="./js/jq.js"></script>
    <script src="./js/bootstrap.js"></script>
    <script>
        let token = sessionStorage.getItem('token');

        let loginUser = null;
        $(function (){

            upatelogindiv();
        })

        function upatelogindiv(){
            const loginUserStr = sessionStorage.getItem('loginUser');
            console.log(token)
            console.log(loginUserStr)
            if (loginUserStr != null) {
                loginUser = JSON.parse(loginUserStr);
                console.log(loginUser);
            }

            $("#login-div").empty();
            if(token){
                $("#login-div").append(`
                <div class="welcome">
                    <img  src="http://127.0.0.1:8081/weibo/users/${loginUser.avatarUrl}"/>
                    <p>欢迎:${loginUser.nickname}</p>
                </div>

                <button onclick="logout()" type="button" class="btn btn-info">退出</button>`)
            }else{
                $("#login-div").append(` <a href="login.html">还没登录？</a>`)
            }
        }

        function logout(){
            //后端退出
            $.getJSON("http://localhost:8081/weibo/user/logout?token="+token,function (res){
                if(res.code == 200){
                    //前端退出
                    sessionStorage.removeItem('loginUser');
                    sessionStorage.removeItem('token');
                    token = null
                    upatelogindiv()
                    alert("退出成功");
                }
            })


        }
    </script>
    <script>
        function loadlist(){
            $.getJSON("http://localhost:8081/weibo/blog/list", function (res){
                $(".list-group").empty();
                res.data.forEach(blog => {
                    let imgshtml = "";
                    blog.imgs.forEach(img => {
                        imgshtml += ` <img class="blog-img" src="http://127.0.0.1:8081/weibo/${img.url}"/>`;
                    });
                    const template = `
                    <li class="list-group-item" onclick="showOne(${blog.blogId})">
                        <div>
                            <div class="item-header clear">
                                <img class="avatarUrl" src="http://127.0.0.1:8081/weibo/users/${blog.user.avatarUrl}"/>
                                <div class="user-header">
                                    <div class="nickname">${blog.user.nickname}</div>
                                    <div class="createdTime">${blog.createdTime}</div>
                                </div>
                            </div>
                            <div class="item-content" >
                                ${blog.content}
                            </div>
                             <div class="imgs">
                                ${imgshtml}
                            </div>
                        </div>
                    </li>`;
                    $(".list-group").append(template);
                });
            });
        }

        function showOne(blogId){
            location.href = "blog.html?blogId=" + blogId;
        }

        $(function (){
            loadlist();
        });

        function showModal(){
            if(token == null){
                alert("请登录")
                return
            }
            $("#content").val("")
            $('#myModal').modal('show');
        }

        let selectedFiles = [];

        function handleFileSelect(event) {
            let files = event.target.files;
            for (let i = 0; i < files.length; i++) {
                selectedFiles.push(files[i]);
                let reader = new FileReader();
                reader.onload = function(e) {
                    const temp =
                        ` <div class="post-img" id="post-img-${i}">
                            <img class="blog-img" src="${e.target.result}"/><br/>
                            <button onclick="delImg(${i})">删除</button>
                        </div>`;
                     $(".post-imgs").prepend(temp);
                };
                reader.readAsDataURL(files[i]);
            }
        }

        function delImg(index){
            $(`#post-img-${index}`).remove()
            selectedFiles.splice(index, 1)
            console.log(selectedFiles)
        }

        function save() {
            let content = $("#content").val();

            if (!content.trim()) {
                alert('博客内容不能为空');
                return;
            }

            let formData = new FormData();
            formData.append('content', content);
            formData.append("token",token)
            selectedFiles.forEach((file, index) => {
                formData.append(`file${index}`, file);
            });

            $.ajax({
                url: 'http://localhost:8081/weibo/blog/save',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.code==200) {
                        alert('博客发布成功');
                        $('#myModal').modal('hide');
                        loadlist();
                    } else {
                        alert('博客发布失败：' + response.message);
                    }
                },
                error: function() {
                    alert('博客发布失败，请稍后重试');
                }
            });
        }
    </script>

</head>
<body>
<div class="container">
    <div class="page-header">
        <h1><a href="index.html">博客jquery</a>  <small>首页</small></h1>
        <div class="login-div" id="login-div">
            <img class="avatarUrl" src="http://127.0.0.1:8081/weibo/users/3.jpg"/>
            <span>欢迎:xxx</span>
            <a href="login.html">还没登录？</a>
        </div>
    </div>
    <div class="fadiv">
        <button id="fabtn" onclick="showModal()" type="button" class="btn btn-primary btn-lg">发blog</button>

    </div>
    <ul class="list-group">
        <!-- 列表项 -->
    </ul>
</div>

<!-- 模态框 -->
<div aria-hidden="true" aria-labelledby="myModalLabel" class="modal fade" id="myModal" role="dialog" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <textarea id="content" class="form-control" rows="3"></textarea>
            </div>
            <hr/>
            <div class="post-imgs clear">
                <div class="post-img-add" onclick="document.getElementById('fileInput').click();">+</div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal" type="button">关闭</button>
                <button class="btn btn-primary" onclick="save()" type="button">提交</button>
            </div>
        </div>
    </div>
</div>

<input type="file" id="fileInput" style="display:none" multiple onchange="handleFileSelect(event)">
</body>
</html>
